package com.star.eastern.blee.fragments

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.inputmethodservice.ExtractEditText
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.RadioGroup
import android.widget.TextView
import android.widget.ToggleButton
import com.star.eastern.blee.MainActivity
import com.star.eastern.blee.R
import com.star.eastern.blee.utils.Tripple7BluetoothCommandProtocol
import com.star.eastern.blee.utils.activity
import com.tangula.android.utils.TaskUtils
import com.tangula.android.utils.ToastUtils
import kotlinx.android.synthetic.main.device_layout.*
import java.lang.Exception
import java.util.*

class DevicePage : Fragment() {


    var cdcRadio: RadioGroup? = null
    //var off1: RadioButton?=null
    //var on1: RadioButton?=null
    var irRadio: RadioGroup? = null
    //var off2: RadioButton?=null
    //var on2: RadioButton?=null
    var learnBtn: Button? = null
    var s1Btn: ToggleButton? = null
    var s2Btn: ToggleButton? = null
    var s3Btn: ToggleButton? = null
    var s4Btn: ToggleButton? = null
    var s5Btn: ToggleButton? = null
    var s6Btn: ToggleButton? = null
    var s7Btn: ToggleButton? = null
    var s8Btn: ToggleButton? = null
    var s9Btn: ToggleButton? = null
    var s10Btn: ToggleButton? = null
    var devicenameView: ExtractEditText? = null
    var applyBtn: Button? = null
    var leanFlag = 0

    var state: Int = 0

    var wantCec = -1
    var wantIr =-1
    var wantLearn = -1

    override fun onResume() {
        //Log.v("console", "device page resume")
        super.onResume()
        updateDeviceName()
    }


    fun updateDeviceName() {
        val name = Tripple7BluetoothCommandProtocol.getDeviceName()
        vw_name_text.text = name
    }

    fun onStatusUpdate(stat:String){
        try {
            val st = stat.removePrefix("STAT")
            if (Tripple7BluetoothCommandProtocol.isIrOn(st)) {
                if(wantIr<0) {
                    irRadio?.check(R.id.offer)
                }else if(wantIr==1){
                    wantIr = -1
                }
            } else {
                if(wantIr<0) {
                    irRadio?.check(R.id.search)
                }else if(wantIr==0){
                    wantIr = -1
                }
            }

            if (Tripple7BluetoothCommandProtocol.isCecOn(st)) {
                if(wantCec<0) {
                    cdcRadio?.check(R.id.offer)
                }else if(wantCec==1){
                    wantCec = -1
                }
            } else {
                if(wantCec<0) {
                    cdcRadio?.check(R.id.search)
                }else if(wantCec==0){
                    wantCec = -1
                }
            }

            leanFlag = if (Tripple7BluetoothCommandProtocol.isLeanOn(st)) {
                if(wantLearn<0) {
                    1
                }else if(wantLearn==1){
                    wantCec = -1
                    1
                }else{
                    leanFlag
                }
            } else {
                if(wantLearn<0) {
                    0
                }else if(wantLearn==0){
                    wantCec = -1
                    0
                }else{
                    leanFlag
                }
            }
            updateLearnButtonColor()
        }catch (e:Exception){
            Log.e("console", e.localizedMessage, e)
        }
    }

    fun updateStatus() {
    }

    @SuppressLint("NewApi")
    override fun onCreateView(inflater: LayoutInflater, parent: ViewGroup?, savedInstanceState: Bundle?): View? {

        //Log.v("console", "device page create view")
        // Defines the xml file for the fragment
        val view = inflater.inflate(R.layout.device_layout, parent, false)

        cdcRadio = view.findViewById<View>(R.id.vw_off_on_front).findViewById(R.id.toggle)
        //off1 = cdcRadio!!.findViewById(R.id.search)
        //on1 = cdcRadio!!.findViewById(R.id.offer)
        irRadio = view.findViewById<View>(R.id.vw_off_on_behind).findViewById(R.id.toggle)
        //off2 = irRadio!!.findViewById(R.id.search)
        //on2 = irRadio!!.findViewById(R.id.offer)
        learnBtn = view.findViewById(R.id.vw_learn_button)
        s1Btn = view.findViewById(R.id.vw_button_s1)
        s2Btn = view.findViewById(R.id.vw_button_s2)
        s3Btn = view.findViewById(R.id.vw_button_s3)
        s4Btn = view.findViewById(R.id.vw_button_s4)
        s5Btn = view.findViewById(R.id.vw_button_s5)
        s6Btn = view.findViewById(R.id.vw_button_s6)
        s7Btn = view.findViewById(R.id.vw_button_s7)
        s8Btn = view.findViewById(R.id.vw_button_s8)
        s9Btn = view.findViewById(R.id.vw_button_s9)
        s10Btn = view.findViewById(R.id.vw_button_s10)
        devicenameView = view.findViewById(R.id.et_devicename)
        applyBtn = view.findViewById(R.id.btn_apply)

        state = 0

        val buttons = arrayOf(s1Btn, s2Btn, s3Btn, s4Btn, s5Btn, s6Btn, s7Btn, s8Btn, s9Btn, s10Btn)

        cdcRadio?.also {
            it.setOnCheckedChangeListener { _, id ->
                onError2Scan {
                    if (id == R.id.offer) {
                        wantCec = 1
                        Tripple7BluetoothCommandProtocol.sendCmdCE1({
                        }) {
                        }
                    } else {
                        wantCec = 0
                        Tripple7BluetoothCommandProtocol.sendCmdCE0({
                        }) {}
                    }
                }
            }
        }

        irRadio?.also {
            it.setOnCheckedChangeListener { _, id ->
                onError2Scan {
                    if (id == R.id.offer) {
                        wantIr=1
                        Tripple7BluetoothCommandProtocol.sendCmdIR1({

                        }) {}
                    } else {
                        wantIr=0
                        Tripple7BluetoothCommandProtocol.sendCmdIR0({

                        }) {}
                    }

                }
            }
        }

        //flag状态  1--学习模式  0--非学习模式
        learnBtn!!.setOnClickListener {
            this.devicenameView?.clearFocus()
            this.applyBtn?.requestFocus()
            if (leanFlag == 0) {
                alertLearn()
            } else {
                wantLearn = 0
                leanFlag = 0
                updateLearnButtonColor()
                setAllBtnDefault()
            }
        }

        val btnClick = { btn: ToggleButton, task: () -> Unit ->
            if (!(btn).isChecked) {
                btn.isChecked = true
            } else {
                onError2Scan {
                    task()
                }

                buttons.forEach { self ->
                    if (self != btn && self!!.isChecked) self.isChecked = false
                }
            }
        }

        s1Btn!!.setOnClickListener {
            btnClick(it as ToggleButton) {
                if (leanFlag == 1) {
                    Tripple7BluetoothCommandProtocol.sendCmdL1({
                        updateStatus()
                        it.setBackgroundResource(R.drawable.ic_launcher_background_purple)
                    }) {}
                } else {
                    Tripple7BluetoothCommandProtocol.sendCmdR1 {
                        updateStatus()
                    }
                }
            }
        }
        s2Btn!!.setOnClickListener {
            btnClick(it as ToggleButton) {
                if (leanFlag == 1) {
                    Tripple7BluetoothCommandProtocol.sendCmdL2({
                        updateStatus()
                        it.setBackgroundResource(R.drawable.ic_launcher_background_purple)
                    }) {}
                } else {
                    Tripple7BluetoothCommandProtocol.sendCmdR2 {
                        updateStatus()
                    }
                }
            }
        }
        s3Btn!!.setOnClickListener {

            btnClick(it as ToggleButton) {
                if (leanFlag == 1) {
                    Tripple7BluetoothCommandProtocol.sendCmdL3({
                        updateStatus()
                        it.setBackgroundResource(R.drawable.ic_launcher_background_purple)
                    }) {}
                } else {
                    Tripple7BluetoothCommandProtocol.sendCmdR3 {
                        updateStatus()
                    }
                }
            }
        }
        s4Btn!!.setOnClickListener {

            btnClick(it as ToggleButton) {
                if (leanFlag == 1) {
                    Tripple7BluetoothCommandProtocol.sendCmdL4({
                        updateStatus()
                        it.setBackgroundResource(R.drawable.ic_launcher_background_purple)
                    }) {}
                } else {
                    Tripple7BluetoothCommandProtocol.sendCmdR4 {
                        updateStatus()
                    }
                }
            }
        }
        s5Btn!!.setOnClickListener {

            btnClick(it as ToggleButton) {
                if (leanFlag == 1) {
                    Tripple7BluetoothCommandProtocol.sendCmdL5({
                        updateStatus()
                        it.setBackgroundResource(R.drawable.ic_launcher_background_purple)
                    }) {}
                } else {
                    Tripple7BluetoothCommandProtocol.sendCmdR5 {
                        updateStatus()
                    }
                }
            }
        }
        s6Btn!!.setOnClickListener {

            btnClick(it as ToggleButton) {
                if (leanFlag == 1) {
                    Tripple7BluetoothCommandProtocol.sendCmdL6({
                        updateStatus()
                        it.setBackgroundResource(R.drawable.ic_launcher_background_purple)
                    }) {}
                } else {
                    Tripple7BluetoothCommandProtocol.sendCmdR6 {
                        updateStatus()
                    }
                }
            }
        }
        s7Btn!!.setOnClickListener {

            btnClick(it as ToggleButton) {
                if (leanFlag == 1) {
                    Tripple7BluetoothCommandProtocol.sendCmdL7({
                        updateStatus()
                        it.setBackgroundResource(R.drawable.ic_launcher_background_purple)
                    }) {}
                } else {
                    Tripple7BluetoothCommandProtocol.sendCmdR7 {
                        updateStatus()
                    }
                }
            }
        }
        s8Btn!!.setOnClickListener {

            btnClick(it as ToggleButton) {
                if (leanFlag == 1) {
                    Tripple7BluetoothCommandProtocol.sendCmdL8({
                        updateStatus()
                        it.setBackgroundResource(R.drawable.ic_launcher_background_purple)
                    }) {}
                } else {
                    Tripple7BluetoothCommandProtocol.sendCmdR8 {
                        updateStatus()
                    }
                }
            }
        }
        s9Btn!!.setOnClickListener {

            btnClick(it as ToggleButton) {
                if (leanFlag == 1) {
                    Tripple7BluetoothCommandProtocol.sendCmdL9({
                        updateStatus()
                        it.setBackgroundResource(R.drawable.ic_launcher_background_purple)
                    }) {}
                } else {
                    Tripple7BluetoothCommandProtocol.sendCmdR9 {
                        updateStatus()
                    }
                }
            }
        }
        s10Btn!!.setOnClickListener {

            btnClick(it as ToggleButton) {
                if (leanFlag == 1) {
                    Tripple7BluetoothCommandProtocol.sendCmdL10({
                        updateStatus()
                        it.setBackgroundResource(R.drawable.ic_launcher_background_purple)
                    }) {}
                } else {
                    Tripple7BluetoothCommandProtocol.sendCmdR10 {
                        updateStatus()
                    }
                }
            }
        }


        applyBtn!!.setOnClickListener {

            val imm = (activity as MainActivity)
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(this.devicenameView!!.getWindowToken(), 0)
            val msg = this.devicenameView?.text.toString()
            Tripple7BluetoothCommandProtocol.sendCmdGreatingMessage(
                msg.substring(
                    0,
                    if (msg.length < 20) msg.length else 20
                ), {
                    updateStatus()
                    this.devicenameView?.setText("")
                }) {}
        }
        applyBtn!!.setBackgroundColor((getResources().getColor(R.color.normalButtonDisabled)))


        devicenameView!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, start: Int, before: Int, after: Int) {
            }

            override fun onTextChanged(charSequence: CharSequence, starrt: Int, before: Int, after: Int) {
            }

            override fun afterTextChanged(editable: Editable) {

                if (devicenameView!!.length() >= 1) {
                    //到1位时是蓝色
                    applyBtn!!.setBackgroundColor(getResources().getColor(R.color.colorMain))
                } else {
                    //没到1位是灰色
                    applyBtn!!.setBackgroundColor(getResources().getColor(R.color.normalButtonDisabled))
                }
                if (devicenameView!!.length() >= 20) {
                    ToastUtils.showToastShort(getString(R.string.max_text_device))
                }
            }


        })

        devicenameView?.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(p0: View?, p1: MotionEvent?): Boolean {

                val inputManager = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
                inputManager.hideSoftInputFromWindow(devicenameView!!.getWindowToken(), 0)
                inputManager.showSoftInput(devicenameView!!, InputMethodManager.SHOW_FORCED)
                return false
            }

        })

        return view
    }

    private fun setAllBtnDefault() {
        listOf(s1Btn, s2Btn, s3Btn, s4Btn, s5Btn, s6Btn, s7Btn, s8Btn, s9Btn, s10Btn).forEach {
            it?.isChecked = false
            it?.setBackgroundResource(R.drawable.gridviewitem)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    fun alertLearn() {
        val dialog = AlertDialog.Builder(Objects.requireNonNull<FragmentActivity>(this.activity))
            .setTitle(this.getString(R.string.learn_remote))
            .setIcon(R.drawable.logo)
            .setMessage(this.getString(R.string.device_alert))
            .setPositiveButton("ok") { _, _ ->
                wantLearn = 1
                leanFlag = 1
                updateLearnButtonColor()
                setAllBtnDefault()
            }
            .setNegativeButton("cancle", null)
            .show()
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorMain))
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor((getResources().getColor(R.color.colorMain)))

        devicenameView?.clearFocus()
    }


    fun updateLearnButtonColor() {
        TaskUtils.runInUiThread {
            try {
                if (leanFlag == 0) {
                    learnBtn!!.background = resources.getDrawable(R.drawable.ic_launcher_background_gray)
                    learnBtn!!.setText(R.string.learning_btn_default)
                } else {
                    learnBtn!!.background = resources.getDrawable(R.drawable.ic_launcher_background_green)
                    learnBtn!!.setText(R.string.learning_btn_text)
                }
            }catch (e:Exception){
                //SKIP
            }
        }
    }

    fun onError2Scan(task: () -> Unit) {
        (activity as MainActivity).onError2Scan(task)
    }


}
